// src/navigation/hooks/useNavigationGuard.ts
import { useEffect } from 'react';
import { useNavigation } from '@react-navigation/native';
import { useSelector } from 'react-redux';
import { RootState } from '../../store/store';
import { RootStackParamList } from '../types.ts'
import { StackNavigationProp } from '@react-navigation/stack';

interface NavigationGuardOptions {
  requireAuth?: boolean;
  requireSubscription?: 'BASIC' | 'PREMIUM';
  redirectTo?: string;
}

type NavigationProp = StackNavigationProp<RootStackParamList>;

export const useNavigationGuard = (options: NavigationGuardOptions = {}) => {
  // 👈 Step 2: Apply the type to the hook
  const navigation = useNavigation<NavigationProp>();
  const { isAuthenticated } = useSelector((state: RootState) => state.auth);
  const { subscription } = useSelector((state: RootState) => state.subscription);

  useEffect(() => {
    // 检查认证
    if (options.requireAuth && !isAuthenticated) {
      // This will now be type-safe
      navigation.reset({
        index: 0,
        routes: [{ name: 'Auth' }],
      });
      return;
    }

    // 检查订阅
    if (options.requireSubscription) {
      const hasRequiredSubscription =
        subscription?.plan === options.requireSubscription ||
        (options.requireSubscription === 'BASIC' && subscription?.plan === 'PREMIUM');

      if (!hasRequiredSubscription) {
        // This will also be type-safe
        navigation.navigate('Subscription');
        return;
      }
    }
  }, [isAuthenticated, subscription, options]);
};